package com.baidu.iit.pxp.el;

import com.baidu.iit.pxp.ActivityClassLoadingException;
import com.baidu.iit.pxp.util.ReflectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.lang.reflect.Constructor;
import java.util.Properties;

/**
 * User: huangweili
 * Date: 14-4-29
 * Time: 下午2:01
 */
public abstract class ExpressionFactory {

    private static Logger logger = LoggerFactory.getLogger(ExpressionFactory.class);

    public static ExpressionFactory newInstance() {
        return newInstance(null);
    }


    public static ExpressionFactory newInstance(Properties properties) {
        ClassLoader classLoader;
        try {
            classLoader = Thread.currentThread().getContextClassLoader();
        } catch (SecurityException e) {
            classLoader = ExpressionFactory.class.getClassLoader();
        }

        String className = null;

        String serviceId = "META-INF/services/" + ExpressionFactory.class.getName();
        InputStream input = ReflectUtil.getResourceAsStream(serviceId);
        try {
            if (input != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
                className = reader.readLine();
                reader.close();
            }
        } catch (IOException e) {
            // do nothing
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (Exception io) {
                    io.printStackTrace();
                } finally {
                    input = null;
                }
            }
        }

        if (className == null || className.trim().length() == 0) {
            try {
                String home = System.getProperty("java.home");
                if (home != null) {
                    String path = home + File.separator + "lib" + File.separator + "el.properties";
                    File file = new File(path);
                    if (file.exists()) {
                        input = new FileInputStream(file);
                        Properties props = new Properties();
                        props.load(input);
                        className = props.getProperty(ExpressionFactory.class.getName());
                    }
                }
            } catch (IOException e) {
                // do nothing
            } catch (SecurityException e) {
                // do nothing
            } finally {
                if (input != null) {
                    try {
                        input.close();
                    } catch (IOException io) {
                        // do nothing
                    } finally {
                        input = null;
                    }
                }
            }
        }

        if (className == null || className.trim().length() == 0) {
            try {
                className = System.getProperty(ExpressionFactory.class.getName());
            } catch (Exception se) {
                se.printStackTrace();
            }
        }

        if (className == null || className.trim().length() == 0) {
            className = "com.baidu.iit.pxp.el.ExpressionFactoryImpl";
        }

        return newInstance(properties, className);
    }


    private static ExpressionFactory newInstance(Properties properties, String className) {
        Class<?> clazz = null;
        try {
            clazz = ReflectUtil.loadClass(className.trim());
            if (!ExpressionFactory.class.isAssignableFrom(clazz)) {
                throw new ELException("Invalid expression factory class: " + clazz.getName());
            }
        } catch (ActivityClassLoadingException e) {
            throw new ELException("Could not find expression factory class", e);
        }
        try {
            if (properties != null) {
                Constructor<?> constructor = null;
                try {
                    constructor = clazz.getConstructor(Properties.class);
                } catch (Exception e) {
                }
                if (constructor != null) {
                    return (ExpressionFactory) constructor.newInstance(properties);
                }
            }
            return (ExpressionFactory) clazz.newInstance();
        } catch (Exception e) {
            throw new ELException("Could not create expression factory instance", e);
        }
    }


    public abstract Object coerceToType(Object obj, Class<?> targetType);


    public abstract MethodExpression createMethodExpression(ELContext context, String expression,
                                                            Class<?> expectedReturnType, Class<?>[] expectedParamTypes);


    public abstract ValueExpression createValueExpression(ELContext context, String expression, Class<?> expectedType);


    public abstract ValueExpression createValueExpression(Object instance, Class<?> expectedType);
}
